package com.crland.tools;

import com.crland.Config.Config;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

public class GetPicture {
    private Logger logger = LoggerFactory.getLogger(getClass());

    public void httpGet(String url, String fileName) {
        try {
            Config config = new Config();
            HttpClient client = HttpClients.createDefault();
            HttpPost post = new HttpPost(url);
            HttpResponse response = client.execute(post);
            Header[] headers = response.getAllHeaders();
            String cookiesAll = "";
            for (Header header : headers) {
                if ("Set-Cookie".equals(header.getName())) {
                    cookiesAll = cookiesAll + header.getValue();
                }
            }
            String[] strings = cookiesAll.split(";");
            String cookie = strings[0] + ";";

            HttpGet get = new HttpGet(url);
            get.addHeader(new BasicHeader("Cookie", cookie));
            HttpResponse response1 = client.execute(get);
            if (response1.getStatusLine().getStatusCode() == 200) {
                byte[] b = EntityUtils.toByteArray(response1.getEntity());
                //文件保存位置
                File saveDir = new File(config.getDownloadPath());
                if (!saveDir.exists()) {
                    saveDir.mkdir();
                }
                File file = new File(saveDir + File.separator + fileName);
                FileOutputStream fos = new FileOutputStream(file);
                fos.write(b);
                fos.close();
                logger.info(fileName + "下载成功");
            }
        } catch (Exception e) {
            logger.error(e.toString());
        }

    }

}
